package com.blensmile.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.PorterDuff;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ViewFlipper;

import com.blensmile.R;
import com.blensmile.utils.DensityUtils;
import com.blensmile.utils.MediaPlayerHelper;

//how to use:
//layout_height and layout_width should be wrap_content or match_parent,if set accurant value, circle would be oval
//set pcv_radius to set the size of circle
//set pcv_color to set background color filter

public class PlayVoiceCircleView extends LinearLayout implements MediaPlayerHelper.CallBack{

    private static long lastClick = 0;
    private View rlVoice;
    private ImageView imgVoice;
    private ViewFlipper vfVoice;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0x11:
                    startPlayingAnim();
                    break;
                case 0x22:
                    setDefaultIcon();
                    break;
            }
        }
    };
    private String soundUrl = "";
    private MediaPlayerHelper helper;
    private RotateAnimation rotateAnim;
    private PlayVoiceCallback callback;

    public PlayVoiceCircleView(Context context) {
        this(context,null);
    }

    public PlayVoiceCircleView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public PlayVoiceCircleView(final Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PlvCircleStyle);
        int radius = (int)a.getDimension(R.styleable.PlvCircleStyle_pcv_radius, DensityUtils.dip2px(context,36));
        int color = a.getColor(R.styleable.PlvCircleStyle_pcv_color,0xff478ffb);
        a.recycle();
        LayoutInflater.from(context).inflate(R.layout.voice_circle_layout,this);
        imgVoice = (ImageView)findViewById(R.id.img_voice);
        vfVoice = (ViewFlipper)findViewById(R.id.vf_voice);
        rlVoice = findViewById(R.id.rl_voice);
        rlVoice.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);
        ViewGroup.LayoutParams params = rlVoice.getLayoutParams();
        params.width = radius;
        params.height =radius;
        if(radius < DensityUtils.px2dip(context,36)){
            ViewGroup.LayoutParams imgParams = imgVoice.getLayoutParams();
            imgParams.height =radius;
            imgParams.width = radius*5/6;
            ViewGroup.LayoutParams vfParams = vfVoice.getLayoutParams();
            vfParams.height = imgParams.height;
            vfParams.width = imgParams.width;
        }
        int padding = (int)(radius*0.2f);
        imgVoice.setPadding(0,padding,0,padding);
        vfVoice.setPadding(0,padding,0,padding);
        helper = new MediaPlayerHelper(PlayVoiceCircleView.this);
        rotateAnim = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnim.setDuration(1600);
        rotateAnim.setRepeatCount(-1);
        rotateAnim.setInterpolator(new LinearInterpolator());

        rlVoice.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(soundUrl)){
                    if(System.currentTimeMillis()-lastClick<800){
                        return;
                    }
                    if(callback != null){
                        callback.onViewClick();
                    }
                    lastClick = System.currentTimeMillis();
                    //判断是否是重复点击
                    if (helper.isRepetition()) {
                        helper.stopAndRelease();
                    } else {
                        startPreparingAnim();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                helper.play(getContext(), soundUrl);
                            }
                        }).start();
                    }
                }
            }
        });
    }

    /***开始播放动画***/
    private void startPlayingAnim(){
        imgVoice.clearAnimation();
        imgVoice.setVisibility(INVISIBLE);
        vfVoice.startFlipping();
        vfVoice.setVisibility(VISIBLE);
    }

    /***开始旋转的花儿***/
    private void startPreparingAnim(){
        imgVoice.setImageResource(R.drawable.circle_flower);
        imgVoice.startAnimation(rotateAnim);
        vfVoice.setVisibility(INVISIBLE);
    }

    private void setDefaultIcon(){
        vfVoice.stopFlipping();
        vfVoice.setVisibility(INVISIBLE);
        imgVoice.clearAnimation();
        imgVoice.setImageResource(R.drawable.voice3b);
        imgVoice.setVisibility(VISIBLE);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if(!TextUtils.isEmpty(MediaPlayerHelper.mPlayingUrl) && MediaPlayerHelper.mPlayingUrl.equals(getSoundUrl())){
            if(helper.isPlaying()){
                startPlayingAnim();
            }else {
                startPreparingAnim();
            }
            helper.registerCallBack();
        }else {
            setDefaultIcon();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        setDefaultIcon();
    }


    public String getSoundUrl() {
        return soundUrl;
    }

    public void setSoundUrl(String soundUrl) {
        this.soundUrl = soundUrl;
    }

    /**实现MediaPlayerUtils的回调接口**/
    @Override
    public void onPlay() {
        handler.sendEmptyMessage(0x11);
    }

    @Override
    public void onStop() {
        handler.sendEmptyMessage(0x22);
    }

    @Override
    public void onErro() {
        handler.sendEmptyMessage(0x22);
    }

    public interface PlayVoiceCallback{
        void onViewClick();
    }

    public PlayVoiceCallback getCallback() {
        return callback;
    }

    public void setCallback(PlayVoiceCallback callback) {
        this.callback = callback;
    }
}
